<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <div style="margin-top: 15px;">
        <el-row :gutter="20">
          <el-col :span="7">
            <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList()"
              @input="getUserList()">
              <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true ">添加用户</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDiglog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">
            </el-button>
            <!-- 提示按键信息，分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>



      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3, 4]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model.number="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 内容底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
      >
      <div>
        <p>当前的用户：{{uesrinfo.username}}</p>
        <p>当前的角色：{{uesrinfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    created() {
      this.getUserList()
    },
    data() {
      //自定义校验规则 验证邮箱的
      var cheackEmail = (rule, val, cb) => {
        //校验邮箱的正则
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if (regEmail.test(val)) {
          return cb()
        }
        cb(new Error('请输入合法的邮箱'))
      }


      //自定义校验规则 验证手机的
      var cheackMobile = (rule, val, cb) => {
        //校验手机的正则
        const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9{8}$]/
        if (regMobile.test(val)) {
          return cb()
        }

        cb(new Error('请输入合法的手机号'))
      }

      return {
        //获取用户列表的参数
        queryInfo: {
          query: '',
          //当前第几页
          pagenum: 1,
          //当前每页显示多少条数据
          pagesize: 1000
        },
        userlist: [],
        total: 0,
        // 属性绑定显示隐藏
        addDialogVisible: false,
        //属性双向绑定
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        //验证规则
        addFormRules: {
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '长度应在3到10个字符之间',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 16,
              message: '长度应在6到16个字符之间',
              trigger: 'blur'
            }
          ],
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            },
            {
              validator: cheackEmail,
              trigger: 'blur'
            }
          ],
          mobile: [{
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              validator: cheackMobile,
              trigger: 'blur'
            }
          ]
        },
        //修改用户对话框的隐藏
        editDialogVisible: false,
        //修改用户对话框的双向绑定,接收根据id查询返回的数据
        editForm: { },
        //修改用户对话框的验证规则
        editFormRules: {
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            },
            {
              validator: cheackEmail,
              trigger: 'blur'
            }
          ],
          mobile: [{
              required: true,
              message: '请输入手机号',
              trigger: 'blur'
            },
            {
              validator: cheackMobile,
              trigger: 'blur'
            }
          ]
        },

        //控制分配角色的显示隐藏
        setRoleDialogVisible:false,
        //scope.row的数据
        uesrinfo:{},
        //所有角色的数据列表
        roleList:[],
        //已选择的角色ID值
        selectRoleId:''

      }
    },
    methods: {
      async getUserList() {
        const {
          data: res
        } = await this.$http.get('users', {
          params: this.queryInfo
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('列表获取失败')
        this.userlist = res.data.users
        this.total = res.data.total
        // console.log(res)
      },
      //监听 pagesize 改变事件
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      // 监听 页面值 改变事件
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      //监听 switch 开关状态的改变
      async userStateChange(userinfo) {
        // console.log(userinfo)
        const {
          data: res
        } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        // console.log(res)
        if (res.meta.status !== 200) {
          userinfo.mg_state = !userinfo.mg_state;
          return this.$message.error('更新用户状态失败');
        }

        this.$message.success('更新用户状态成功')
      },
      //监听添加用户表单的关闭时事件
      addDialogClose() {
        this.$refs.addFormRef.resetFields()
      },
      //点击确定对表单进行验证，添加用户
      addUser() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return
          //通过了 可以发起请求
          const {
            data: res
          } = await this.$http.post('users', this.addForm)
          if (res.meta.status !== 201) {
            this.$message.error('用户没有添加成功')
          }
          this.$message.success('用户添加成功')
          //隐藏对话框
          this.addDialogVisible = false
          //重新获取用户列表
          this.getUserList()
        })
      },
      //展示用户的对话框
      async showEditDiglog(id) {
        this.editDialogVisible = true
        //获取用户信息
        const {
          data: res
        } = await this.$http.get(`users/${id}`)
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('查询不到此用户信息')
        }
        this.editForm = res.data
        this.$message.success('成功查询此用户信息')

      },
      //监听修改用户对话框的关闭事件
      editDialogClose() {
        this.$refs.editFormRef.resetFields()
      },
      //修改用户信息提交
      editUserInfo() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return
          //通过了 可以发起请求
          const {
            data: res
          } = await this.$http.put(`users/${this.editForm.id}`, this.editForm)
          // console.log(res)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          //关闭对话框
          this.editDialogVisible = false
          //刷新列表
          this.getUserList()
          //用户提示
          this.$message.success(res.meta.msg)
        })
      },
      //根据用户的ID删除用户
      async removeUserById(id) {
        const comfirmRes = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        //confirm 确定删除
        //cancel  取消删除
        if(comfirmRes !== "confirm") {
          return this.$message.info("已经取消了删除")
        }

        const {data : res } = await this.$http.delete(`users/${id}`)
        // console.log(res)
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getUserList()

      },
      //展示分配角色对话框
      async setRole(userinfo){
        this.uesrinfo = userinfo
        //获取所有角色列表
        const {data:res} = await this.$http.get('roles')
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg)
        }

        this.roleList = res.data
        this.setRoleDialogVisible = true
      },
      //分配角色
      async saveRoleInfo(){
        if(!this.selectRoleId){
          return this.$message.error('请选择你分配的角色!!!')
        }

        const {data:res} = await this.$http.put(`users/${this.uesrinfo.id}/role`,{rid : this.selectRoleId})
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg)
        }


        this.getUserList()
        this.setRoleDialogVisible = false
        this.$message.success(res.meta.msg)

      },
      //对话框的重置
      setRoleDialogClosed(){
        this.selectRoleId = ''
        this.userinfo = ''
      }


    }
  }
</script>

<style lang="less" scoped>

</style>
